package com.youchuang.action.indent;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.jboss.logging.Logger;

import com.youchuang.action.BaseAction;
import com.youchuang.action.cart.CartItem;
import com.youchuang.bean.Indent;
import com.youchuang.bean.ReceiveAddress;
import com.youchuang.bean.User;
import com.youchuang.common.Constant;
import com.youchuang.service.CartService;
import com.youchuang.service.IndentService;

/**
 * 提交订单
 * 
 * @author Administrator
 *
 */
@Namespace(value = "/indent")
@ParentPackage("shopping-default")
public class IndentSubmitAction extends BaseAction {
	private Logger logger = Logger.getLogger(IndentSubmitAction.class.getSimpleName());
	private ReceiveAddress addr;
	private Indent indent;

	@Resource
	private IndentService indentService;
	@Resource
	private CartService cartService;

	@Action(value = "indentSubmit", interceptorRefs = { @InterceptorRef(value = "tokenStack") }, results = {
			@Result(name = Constant.SUCCESS, location = "/WEB-INF/jsp/indent/indent_payment.jsp"),
			@Result(name = Constant.EMPTY, type = "redirect", location = "/WEB-INF/jsp/main/main.jsp") })
	public String execute() throws Exception {
		logger.info("excetion is execute");
		if (CollectionUtils.isEmpty(cartService.getItems(false)))
			return Constant.EMPTY;

		String userId = ((User) session.get(Constant.S_USER)).getId();
		addr.setUserId(userId);

		indent = new Indent();
		indent.setFullAddress(addr.getFullAddress());
		indent.setUserId(userId);
		indent.setMobile(addr.getMobile());
		indent.setPaymentMethod(Constant.WAIT_PAYMENT_METHOD);
		indent.setIndentTime(System.currentTimeMillis());
		indent.setPhone(addr.getPhone());
		indent.setPostalCode(addr.getPostalCode());
		indent.setReceiveName(addr.getReceiveName());
		indent.setStatus(Constant.WAIT_PAY);
		indent.setTotalPrice(cartService.total(false));

		List<CartItem> cartItems = cartService.getItems(false);

		indentService.saveIndent(cartItems, indent, addr);

		cartService.clearCart();

		return Constant.SUCCESS;
	}

	public ReceiveAddress getAddr() {
		return addr;
	}

	public void setAddr(ReceiveAddress addr) {
		this.addr = addr;
	}

	public Indent getIndent() {
		return indent;
	}

	public void setIndent(Indent indent) {
		this.indent = indent;
	}
}
